﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text.RegularExpressions;
//using OnlineVideos.ViewModels;
using System.Windows.Media.Imaging;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Text;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using Common.Library;
using OnlineVideos.Data;
using MyToolkit.Multimedia;
using OnlineVideos.UI;
using System.ComponentModel;
using OnlineVideos.Entities;
namespace OnlineVideos
{
    public partial class DownloadPivots : PhoneApplicationPage
    {
        #region GlobalDecularation
        List<string> downloadtitle = new List<string>();
        string[] regexImgSrc = { @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<embed[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<iframe[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<video[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<link[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>" };
        public ObservableCollection<DownloadPivot> Collection { get; set; }
        IEnumerable<DependencyObject> cboxes = null;
        List<DownloadPivot> YoutubeDownloadUrlList = new List<DownloadPivot>();
        public List<string> chkboxes = new List<string>();
        private static string result = null;

        List<Uri> Video = new List<Uri>();
        List<Uri> Audio = new List<Uri>();
        List<Uri> Image = new List<Uri>();
        List<Uri> Link = new List<Uri>();
        List<Uri> comparevideo = new List<Uri>();
        CustomizationSettings objCustom = new CustomizationSettings();
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        string TitleForPromptFile = string.Empty;
        int k = 0; 
        #endregion

        #region Initialize
        public DownloadPivots()
        {
            try
            {
                InitializeComponent();
                LoadPivotThemes();
                Loaded += new RoutedEventHandler(DownloadPivots_Loaded);
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in DownloadPivots Method In DownloadPivots.cs file.", ex);
            }
        } 
        #endregion

        #region Common Methods
        private void GetPageDataInBackground()
        {
            try
            {
                Video.Clear();
                Audio.Clear();
                Image.Clear();
                Link.Clear();
                Constants.SaveImages.Clear();
                Constants.SaveAudios.Clear();
                Constants.SaveVideos.Clear();
                Constants.SaveLinks.Clear();
                performanceProgressBar.IsIndeterminate = true;
                BackgroundHelper bhhelper = new BackgroundHelper();
                bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
                {
                    DownloadManagerHelper.GetWebContent(regexImgSrc);
                },
                    (object s, RunWorkerCompletedEventArgs a) =>
                    {

                        Video.AddRange(Constants.SaveVideos);
                        Audio.AddRange(Constants.SaveAudios);
                        Image.AddRange(Constants.SaveImages);
                        Link.AddRange(Constants.SaveLinks);
                        LoadDownLoadVideos();
                        LoadDownloadAudios();
                        LoadImages();
                        LoadLinks();

                    }
                    );
              

                bhhelper.RunBackgroundWorkers();
                performanceProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                string mess = "Exception in GetPageDataInBackground Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void LoadLinks()
        {
            lbxlinks.Visibility = Visibility.Visible;
            ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
            try
            {

                if (Link.Count() != 0)
                {
                    download = DownloadManagerHelper.LoadLinks(Link);
                    lbxlinks.Visibility = Visibility.Visible;
                    lbxlinks.ItemsSource = download;

                }
                else
                {
                    lbxlinks.Visibility = Visibility.Collapsed;
                    tblkLinks.Visibility = Visibility.Visible;

                }

            }
            catch (Exception ex)
            {
                if (download.Count != 0)
                {
                    lbxlinks.ItemsSource = download;
                    lbxlinks.Visibility = Visibility.Visible;
                }
                else
                {
                    lbxlinks.Visibility = Visibility.Collapsed;
                    tblkLinks.Visibility = Visibility.Visible;

                    Exceptions.SaveOrSendExceptions("Exception in GetVideoLinksOfAMovie Method In OnlineShow.cs file", ex);
                }

            }

        }

        private void LoadImages()
        {
            ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
            try
            {
                string path;
                if (Image.Count() != 0)
                {
                    download = DownloadManagerHelper.LoadImages(Image);

                    lbxname.ItemsSource = download;
                }
                else
                {
                    lbxname.Visibility = Visibility.Collapsed;
                    tblkimages.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in LoadImages Method In downloadpivot.xaml.cs file", ex);
            }
            // performanceProgressBarvideo.IsIndeterminate = false;
        }

        private void LoadDownloadAudios()
        {
            try
            {
                ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
                if (Audio.Count() != 0)
                {
                    lbxAudio.Visibility = Visibility.Visible;
                    tblkAudio.Visibility = Visibility.Collapsed;
                    Collection = DownloadManagerHelper.LoadAudios(Audio);
                    lbxAudio.ItemsSource = Collection;
                }
                else
                {
                    lbxAudio.Visibility = Visibility.Collapsed;
                    tblkAudio.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in LoadDownloadAudios Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void LoadDownLoadVideos()
        {
            try
            {
                performanceProgressBarVideo.IsIndeterminate = true;
                ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
                if (Video.Count() != 0)
                {
                    string path = "";
                    int j = 0;
                    bool fal = false;
                    foreach (Uri u in Video)
                    {
                        if (u.ToString().StartsWith("http://"))
                        {
                            if (u.ToString().StartsWith("http://www.youtube.com/v/"))
                            {
                                //Load the youtube videos on pivote page
                                LoadYouTubeVideos(download, ref j, ref fal, u);

                            }
                            else
                            {
                                DownloadPivot d = new DownloadPivot();
                                d.title = u.ToString().Substring(u.ToString().LastIndexOf("/") + 1);
                                d.Downloaduri = u;
                                if (d.title != "")
                                    download.Add(d);
                            }
                        }
                        else
                        {
                            DownloadPivot d = new DownloadPivot();
                            path = AppSettings.starturidownloadmanger + u.AbsolutePath.ToString();
                            d.title = path.Substring(path.ToString().LastIndexOf("/") + 1);
                            d.Downloaduri = new Uri(path);
                            if (d.title != "")
                                download.Add(d);
                        }
                    }

                    lbxVideo.ItemsSource = download;
                    lbxVideo.Visibility = Visibility.Visible;
                    YoutubeDownloadUrlList.AddRange(download);
                   
                }
                else
                {
                    lbxVideo.Visibility = Visibility.Collapsed;
                    tblkFavNoMovies.Visibility = Visibility.Visible;
                    performanceProgressBarVideo.IsIndeterminate = false;
                }

            }
            catch (Exception ex)
            {
                string mess = "Exception in LoadDownLoadVideos Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
            if (lbxVideo.Items.Count != 0)
            {
                performanceProgressBarVideo.IsIndeterminate = false;
            }
        }

        private void LoadYouTubeVideos(ObservableCollection<DownloadPivot> download, ref int j, ref bool fal, Uri u)
        {
            try
            {
                int count = Video.Count + k;
                if (Video.Count != downloadtitle.Count)
                {
                    if (fal != true)
                    {
                        Uri g = Video.ElementAt(k);
                        string youtubeurl = g.ToString().Substring(g.ToString().LastIndexOf("v/") + 2);
                        string yurl = youtubeurl.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "");
                        GetYoutubeTitle("http://www.youtube.com/watch?v=" + yurl);
                        fal = true;
                        k++;
                    }
                }
                if (Video.Count == downloadtitle.Count)
                {
                    bool f = false;
                    for (int i = j; i < downloadtitle.Count; i++)
                    {
                        if (f != true)
                        {
                            DownloadPivot d = new DownloadPivot();

                            d.title = downloadtitle.ElementAt(i).Split('@')[0];
                            d.YoutubeUrl = downloadtitle.ElementAt(i).Split('@')[1];
                            d.Downloaduri = u;
                            string youtubeurl = u.ToString().Substring(u.ToString().LastIndexOf("v/") + 2);
                            string yurl = youtubeurl.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "");
                            d.DownLoadVideoImage = "http://img.youtube.com/vi/" + yurl + "/default.jpg";
                            if (!downloadtitle.ElementAt(i).Split('@')[1].Contains("http://www.youtube.com/Faild"))
                                download.Add(d);
                            f = true;
                            j++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in LoadYouTubeVideos Method In DownloadPivots.cs file.", ex);
            }
        }

        private void LoadPivotThemes()
        {

        }

        public void GetYoutubeTitle(string uri)
        {
            try
            {
                WebClient wcl = new WebClient();
                wcl.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                wcl.DownloadStringCompleted += wcl_DownloadStringCompleted;
                wcl.DownloadStringAsync(new Uri(uri));
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in GetYoutubeTitle Method In DownloadPivots.cs file.", ex);
            }
        }

        public void ChannelCh()
        {
            try
            {
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                wc.DownloadStringCompleted += WcChannelCh_DownloadStringCompleted;
                wc.DownloadStringAsync(new Uri(AppSettings.NavigationUrl));
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in ChannelCh Method In DownloadPivots.cs file.", ex);
            }

        }
        
        #endregion

        #region Events
       
        void wcl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
               string title=string.Empty;
               string Downloadurl = string.Empty;
                BackgroundHelper bhhelper = new BackgroundHelper();
                bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
                 {
                     title = DownloadManagerHelper.GetTitle(e.Result);
                     Downloadurl = DownloadManagerHelper.GethtmlData(e.Result);
                 },
                     (object s, RunWorkerCompletedEventArgs a) =>
                     {
                         if (title != null)
                         {
                             downloadtitle.Add(title + "@" + Downloadurl);
                         }
                         LoadDownLoadVideos();
                     });
                bhhelper.RunBackgroundWorkers();
            }

            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in wcl_DownloadStringCompleted Method In DownloadPivots.cs file.", ex);
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In DownloadPivots.cs file.", ex);
            }
        }

        void DownloadPivots_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
                FlurryWP8SDK.Api.LogEvent("DownloadPivots Page", true);
                Collection = new ObservableCollection<DownloadPivot>();
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in DownloadPivots_Loaded Method In DownloadPivots.cs file.", ex);
            }
        }

        private void img1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {


        }

        private void checkImages_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxCheckedItemList(lbxname);

            }
            catch (Exception ex)
            {
                string mess = "Exception in checkImages_Checked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void unchckimages_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxUnCheckedItemList(lbxname);
               
            }
            catch (Exception ex)
            {
                string mess = "Exception in unchckimages_Unchecked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void appbar_button1_Click(object sender, EventArgs e)
        {
            try
            {
                BackgroundHelper bhhelper = new BackgroundHelper();
                bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
                {
                    DownloadManagerHelper.AppbarDownloadClick(chkboxes, YoutubeDownloadUrlList);
                },
                    (object s, RunWorkerCompletedEventArgs a) =>
                    {
                        Constants.DownloadStatus = false;
                        NavigationService.Navigate(new Uri("/Views/ShowList.xaml?index=" + 2, UriKind.Relative));

                    });
                bhhelper.RunBackgroundWorkers();
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in appbar_button1_Click Method In DownloadPivots.cs file.", ex);
            }
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Downloding.xaml", UriKind.Relative));
        }

        private void chkAudio_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {

                chkboxes = DownloadManagerHelper.CheckBoxUnCheckedItemList(lbxAudio);
                
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkAudio_Unchecked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void chkAudio_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxCheckedItemList(lbxAudio);
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkAudio_Checked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void chkVideo_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxCheckedItemList(lbxVideo);
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkVideo_Checked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void chkVideo_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxUnCheckedItemList(lbxVideo);
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkVideo_Unchecked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void menuItemdownload_Click(object sender, EventArgs e)
        {
            try
            {
                if (chkboxes.Count() != 0)
                {
                    foreach (string s in chkboxes)
                    {
                        DownloadManager.Savetofolder("", s);


                    }
                    SettingsHelper.Save("DownloadFolder", "0");
                    NavigationService.Navigate(new Uri("/Views/SaveFolderName.xaml", UriKind.Relative));
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in menuItemdownload_Click Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void imgTitle_MouseEnter(object sender, MouseEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void WcChannelCh_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string html = e.Result.ToString();
                string RegexForFrame = @"<frame[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
                MatchCollection fram = Regex.Matches(html, RegexForFrame, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m in fram)
                {
                    string href = m.Groups[1].Value;
                    if (href.ToString().StartsWith("http://sharesix.com"))
                    {
                        WebClient wc12 = new WebClient();
                        wc12.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                        wc12.DownloadStringCompleted += Wcsharesix_DownloadStringCompleted;
                        wc12.DownloadStringAsync(new Uri(href));

                    }
                    if (href.ToString().StartsWith("http://www.promptfile.com"))
                    {
                        WebClient wcpromptfile = new WebClient();
                        wcpromptfile.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                        wcpromptfile.DownloadStringCompleted += wcpromptfile_DownloadStringCompleted;
                        wcpromptfile.DownloadStringAsync(new Uri(href));
                        Match Title = Regex.Match(html, @"\<title\s?.*?\>((.|\r\n)+?)\<\/title\>");
                        TitleForPromptFile = Title.Groups[1].Value;
                    }
                }
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in WcChannelCh_DownloadStringCompleted Method In DownloadPivots.cs file.", ex);
            }
        }

        private void wcpromptfile_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string html1 = e.Result.ToString();
                string Regexfordiv = @"\<div\s?.*?\>((.|\r\n)+?)\<\/div\>";
                MatchCollection fram1 = Regex.Matches(html1, Regexfordiv, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m1 in fram1)
                {

                    Match GetUrl = Regex.Match(m1.ToString(), @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    if (GetUrl.ToString().Contains("http://www.promptfile.com"))
                    {
                        string Url = GetUrl.Groups[1].Value.Replace("==", "");
                        string OriginalUrl = Url + "=" + TitleForPromptFile + ".mkv";
                        Video.Add(new Uri(OriginalUrl));
                        LoadDownLoadVideos();
                        lbxVideo.Visibility = Visibility.Visible;
                        tblkFavNoMovies.Visibility = Visibility.Collapsed;

                    }


                }
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in wcpromptfile_DownloadStringCompleted Method In DownloadPivots.cs file.", ex);
            }
        }

        private void Wcsharesix_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string html1 = e.Result.ToString();
                string Regexforscript = @"\<script\s?.*?\>((.|\r\n)+?)\<\/script\>";
                Match mth = Regex.Match(html1, @"\<Title\s?.*?\>((.|\r\n)+?)\<\/Title\>");
                MatchCollection fram1 = Regex.Matches(html1, Regexforscript, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m1 in fram1)
                {
                    string scriptgroup = m1.Groups[1].Value.Replace("</script>\n", "");
                    if (scriptgroup.StartsWith("<script type='text/javascript'>eval"))
                    {
                        string rate = scriptgroup.Substring(scriptgroup.LastIndexOf("addParam|") + 9).Replace("player|", "");
                        string PlayerUrl = rate.Substring(rate.LastIndexOf("video|") + 6).Split('|')[0];
                        string PlayerID = rate.Split('f')[0].Replace("|", "._").Replace("._._", "");
                        string[] arrayid = PlayerID.Split('_');
                        string orignalid = null;
                        int i = 0;
                        foreach (string s in arrayid.Reverse())
                        {
                            i++;
                            if (arrayid.Count() != i)
                                orignalid = orignalid + s + ".";
                            else
                                orignalid = orignalid + s.Replace(".", "");
                        }
                        string DownloadUrl = "http://" + orignalid.Replace("..", ".") + "/d/" + PlayerUrl + "/" + mth.Groups[1].Value + ".mp4";
                        Video.Add(new Uri(DownloadUrl));
                        LoadDownLoadVideos();
                        lbxVideo.Visibility = Visibility.Visible;
                        tblkFavNoMovies.Visibility = Visibility.Collapsed;

                    }

                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in Wcsharesix_DownloadStringCompleted Method In DownloadPivots.cs file.", ex);
            }
        }

        private void lbxlinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxlinks.SelectedIndex != -1)
            {
                performanceProgressBar.IsIndeterminate = true;

                Uri href = (lbxlinks.SelectedItem as DownloadPivot).Downloaduri;
                try
                {
                    WebClient webcli = new WebClient();
                    webcli.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                    webcli.DownloadStringCompleted += webcli_DownloadStringCompleted;
                    webcli.DownloadStringAsync(new Uri(href.ToString()));
                    AppSettings.NavigationUrl = href.ToString();
                }
                catch (Exception ex)
                {
                    string mess = "Exception in lbxlinks_SelectionChanged Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                    Exceptions.SaveOrSendExceptions(mess, ex);
                }
                lbxlinks.SelectedIndex = -1;

            }
        }

        void webcli_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            try
            {
                tblkimages.Visibility = Visibility.Collapsed;
                tblkAudio.Visibility = Visibility.Collapsed;
                tblkLinks.Visibility = Visibility.Collapsed;
                tblkFavNoMovies.Visibility = Visibility.Collapsed;
                lbxname.Visibility = Visibility.Visible;
                lbxAudio.Visibility = Visibility.Visible;
                lbxVideo.Visibility = Visibility.Visible;
                lbxlinks.Visibility = Visibility.Visible;
                Video.Clear();
                Audio.Clear();
                Image.Clear();
                Link.Clear();
                if (AppSettings.NavigationUrl.StartsWith("http://www.1channel.ch"))
                {
                    ChannelCh();
                }
                if (e.Result != null)
                    AppSettings.htmltextfordownloadmanger = e.Result;
                performanceProgressBar.IsIndeterminate = true;
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in webcli_DownloadStringCompleted Method In DownloadPivots.cs file.", ex);
            }
        }

        private void lbxVideo_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var selecteditem = lbxVideo.SelectedItem as DownloadPivot;
                if (selecteditem.Downloaduri.ToString().StartsWith("http://www.youtube.com"))
                {
                    string linkurl = selecteditem.YoutubeUrl;
                    DownloadManagerHelper.PlayStreamVideo(linkurl);
                }
                else
                {
                    YouTube.LoadYoutubeVideo((selecteditem.Downloaduri.ToString()));
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in lbxVideo_SelectionChanged_1 Method In DownloadPivots.cs file.", ex);
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("DownloadPivots Page");
                IEnumerable<System.Windows.Navigation.JournalEntry> back = NavigationService.BackStack.ToList();
                foreach (var b in back)
                {
                    if (!b.Source.ToString().Contains("MainPage.xaml"))
                        NavigationService.RemoveBackEntry();
                    //break;
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in OnNavigatedFrom Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }
        #endregion
    }
  

}